#include "BK3432_reg.h"
#include "i2c_software_drv.h"
#include "gpio.h"


static uint8_t sck_pin_num;
static uint8_t sda_pin_num;

#define SCL0_HIGH()		  gpio_set(sck_pin_num, 1)
#define SCL0_LOW()		  gpio_set(sck_pin_num, 0)
#define SDA0_HIGH()		  gpio_set(sda_pin_num, 1)
#define SDA0_LOW()		  gpio_set(sda_pin_num, 0)
#define SDA0_SetInput()	  gpio_config(sda_pin_num, INPUT, PULL_NONE)
#define SDA0_SetOutput()  gpio_config(sda_pin_num, OUTPUT, PULL_NONE)
#define SDA0_READ()		  gpio_get_input(sda_pin_num)


static void delay(uint16_t dly_cnt)
{
	while(dly_cnt--);
}

void i2c_start(void)
{
	SDA0_HIGH();
	SCL0_HIGH();
	delay(5);
	SDA0_LOW();
	delay(5);
	SCL0_LOW();
}

void i2c_stop(void)
{
	SDA0_LOW();
	delay(3);
	SCL0_HIGH();
	SDA0_HIGH();
}

uint8_t i2c_tx_byte(uint8_t dat)
{
	uint8_t i;
	for(i=0;i<8;i++)
    {
		if(dat&0x80)
        {
			SDA0_HIGH();
		}
        else
        {
			SDA0_LOW();
		}
		SCL0_HIGH();
		
		SCL0_LOW();
		
		dat<<=1;
	}
	SDA0_SetInput();
    
	SCL0_HIGH();
	
	i=SDA0_READ();
	
	SCL0_LOW();
	SDA0_SetOutput();
	return(i==0);
}


/*uint8_t i2c_rx_byte(char ack)
{
	uint8_t i;
	uint8_t r=0;
	SDA0_SetInput();
	delay(1);
	for(i=0;i<8;i++)
    {
		SCL0_HIGH();
		
		r<<=1;
		if(SDA0_READ())
        {
			r|=1;
		}
		SCL0_LOW();
	}
	SDA0_SetOutput();
	if(ack)
	    SDA0_LOW();
	else
		SDA0_HIGH();
	SCL0_HIGH();
	delay(1);
	SCL0_LOW();
	SDA0_SetInput();
	return(r);
}*/

void i2c_sw_init(uint8_t sck_pin, uint8_t sda_pin)
{
	sck_pin_num = sck_pin;
	sda_pin_num = sda_pin;
    gpio_config(sck_pin_num, OUTPUT, PULL_NONE);
    gpio_config(sda_pin_num, OUTPUT, PULL_NONE);
}

void i2c_tx_data(uint8_t devAddr7, uint8_t addr, uint8_t *buf, int size)
{
	int i;
	i2c_start();
    if(i2c_tx_byte(devAddr7<<1)==0)
    {
		i2c_stop();
		return;
	}
	if(i2c_tx_byte(addr)==0)
	{
		i2c_stop();
		return;
	}
	for(i=0;i<size;i++)
    {
		if(i2c_tx_byte(*buf++)==0)
		{
			i2c_stop();
			return;
		}
	}
	i2c_stop();
}

/*void i2c_rx_data(uint8_t devAddr7, uint8_t addr, uint8_t *buf, int size)
{
	int i;

	i2c_start();
    if(i2c_tx_byte(devAddr7<<1)==0)
	{
		i2c_stop();
		return;
	}
	if(i2c_tx_byte(addr)==0)
	{
		i2c_stop();
		return;
	}
	i2c_start();
	if(i2c_tx_byte((devAddr7<<1)+1)==0)
	{
		i2c_stop();
		return;
	}
	for(i=0;i<(size-1);i++)
    {
		*buf++=i2c_rx_byte(1);
	}
	*buf++=i2c_rx_byte(0);
	SDA0_SetOutput();
	i2c_stop();
}*/


